﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Micrhard.FMCG.Server.Interface;
using Microhard.Core.DBUtility;
using Micrhard.FMCG.Server.DataAccess;
using Micrhard.FMCG.Server.DTO;
using Microhard.Core;
using Micrhard.FMCG.Server.Msg;
using Micrhard.FMCG.Server.Models;

namespace Micrhard.FMCG.Server.Impl
{
    public class CustomerOrderImpl : ICustomerOrder
    {
        public Microhard.Core.DBUtility.ExecutedResult Add(Models.OrderModel model)
        {
            ExecutedResult rtn = new ExecutedResult();
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();

            var op = model.ToEntity();
            op.CreateTime = DateTime.Now;
            int totalCount = db.Orders.Count();

            if (model.OrderTypeSelect == OrderType.KAOrder)
            {
                op.Code = "KA" + (totalCount + 1);
                op.OrderType = (int)OrderType.KAOrder;
                op.KAOrders.Add(new KAOrder
                {
                    KAOrderID = Guid.NewGuid(),
                    CreateTime = op.CreateTime,
                    SubKAID = model.FromKAID
                });
            }
            else if (model.OrderTypeSelect == OrderType.CustomerOrder)
            {
                op.Code = "CUS" + (totalCount + 1);
                op.OrderType = (int)OrderType.CustomerOrder;
                op.CustomerOrders.Add(new CustomerOrder
                {
                    CustomerOrderID = Guid.NewGuid(),
                    CreateTime = op.CreateTime,
                    CustomerID = model.CustomerID
                });
            }
            else
            {
                op.OrderType = (int)OrderType.Promotion;
                op.Code = "CUS" + (totalCount + 1);
                op.CustomerOrders.Add(new CustomerOrder
                {
                    CustomerOrderID = Guid.NewGuid(),
                    CreateTime = op.CreateTime,
                    CustomerID = model.CustomerID
                });
            }
            op.Status = (int)OrderStatus.Save;
            op.CompanyID = this.scope.EmpInfo.CompanyID;
            db.Orders.AddObject(op);

            try
            {
                db.SaveChanges();
            }
            catch (System.Exception ex)
            {
                rtn.ErrorMsg.Add(DBOperationFailedStatus.AddFailed, OrderMsg.AddFailed);
                Log.Error("ICustomerOrder.Add", ex);
            }
            return rtn;
        }

        public Microhard.Core.DBUtility.ExecutedResult Update(Models.OrderModel model)
        {
            ExecutedResult result = new ExecutedResult();
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var entity = db.Orders.SingleOrDefault(o => o.OrderID == model.OrderID);
            if (entity != null)
            {
                entity.DeliveryAddress = model.DeliveryAddress;
                entity.OrderDate = model.OrderDate.ToString("yyyy-MM-dd");
            }
            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                result.ErrorMsg.Add(DBOperationFailedStatus.UpdateFailed, OrderMsg.UpdateFailed);
                Log.Error("ICustomerOrder.Update", ex);
            }
            return result;
        }

        public Microhard.Core.DBUtility.ExecutedResult Delete(List<Guid> ids)
        {
            ExecutedResult result = new ExecutedResult();
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var toDelete = db.Orders.Where(e => ids.Contains(e.OrderID)).ToList();
            try
            {
                toDelete.ForEach(e =>
                {
                    //订单能否删除
                    if (e.Status == (int)OrderStatus.Save)
                    {
                        if (e.CustomerOrders.Count > 0)
                        {
                            e.CustomerOrders.ToList().ForEach(d =>
                            {
                                db.CustomerOrders.DeleteObject(d);
                            });
                        }
                        if (e.KAOrders.Count > 0)
                        {
                            e.KAOrders.ToList().ForEach(d =>
                            {
                                db.KAOrders.DeleteObject(d);
                            });
                        }

                        if (e.OrderDetails.Count > 0)
                        {
                            e.OrderDetails.ToList().ForEach(d =>
                            {
                                db.OrderDetails.DeleteObject(d);
                            });

                        }
                        db.Orders.DeleteObject(e);
                    }
                    else
                    {
                        result.ErrorMsg.Add(DBOperationFailedStatus.DeleteFailed, string.Format(OrderMsg.IsInUsing, e.Code));
                    }
                });
                if (result.ErrorMsg.Count == 0)
                {

                    db.SaveChanges();

                }
            }
            catch (Exception ex)
            {
                result.ErrorMsg.Add(DBOperationFailedStatus.DeleteFailed, OrderMsg.DeleteFailed);
                Log.Error("ICustomerOrder.Delete", ex);
            }
            return result;
        }

        public Microhard.Core.DBUtility.ExecutedResult Delete(Models.OrderModel model)
        {
            throw new NotImplementedException();
        }

        public Models.OrderModel GetModelByID(Guid id)
        {
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var model = db.Orders.SingleOrDefault(c => c.OrderID == id);
            if (model != null)
            {
                return model.ToModel();
            }
            return null;
        }

        public Models.OrderModel GetModelByModel(Models.OrderModel model)
        {
            throw new NotImplementedException();
        }

        public List<Models.OrderModel> Query(Models.OrderModel Model, int pageIndex, int pageSize, out int totalCount)
        {
            totalCount = 0;
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            IEnumerable<Order> entities = null;
            if (!string.IsNullOrEmpty(Model.Code))
            {
                entities = from b in db.Orders
                           where b.Code == Model.Code
                           && b.CompanyID == this.scope.EmpInfo.CompanyID
                           && this.scope.PKID.Contains(b.OrderID)
                           select b;
            }
            else
            {
                entities = from b in db.Orders
                           where b.CompanyID == this.scope.EmpInfo.CompanyID
                           && this.scope.PKID.Contains(b.OrderID)
                           select b;
            }
            if (entities != null)
            {
                totalCount = entities.Count();
                var pagedEntities = entities.OrderBy(p => p.CreateTime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                if (pagedEntities != null && pagedEntities.Count > 0)
                    return pagedEntities.Select(m => m.ToModel()).ToList();
            }
            return new List<OrderModel>();
        }

        public List<Models.OrderModel> Query(Models.OrderModel Model)
        {
            throw new NotImplementedException();
        }

        public Microhard.Core.DBUtility.ScopeResult scope
        {
            set;
            get;
        }

        public void ReopenOrder(Guid orderID)
        {
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var model = db.Orders.SingleOrDefault(c => c.OrderID == orderID);
            if (model != null && model.Status != (int)OrderStatus.Checked)
            {
                model.Status = (int)OrderStatus.Checked;
                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    Log.Error("ICustomerOrder.ReopenOrder", ex);
                }
            }
        }

        public void CloseOrder(Guid orderID)
        {
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            var model = db.Orders.SingleOrDefault(c => c.OrderID == orderID);
            if (model != null && (model.IsSendCoin == null || !model.IsSendCoin.Value))
            {
                model.Status = (int)OrderStatus.Finished;
                model.IsSendCoin = true;
                try
                {
                    //进行积分操作
                    var mainOrder = model.CustomerOrders.First();
                    var customerCoin = db.CustomerCoins.SingleOrDefault(s => s.CustomerID == mainOrder.CustomerID);
                    //获得增加积分产品
                    var newAddCoins = (double)model.OrderDetails.Where(p => p.Product.IsPromotion == false).Sum(s => s.Amount);
                    //获得减分产品
                    var reduceCoins = (double)model.OrderDetails.Where(p => p.Product.IsPromotion == true).Sum(s => s.Amount);
                    //最后赠送积分
                    newAddCoins = newAddCoins - reduceCoins;

                    if (customerCoin != null)
                    {
                        customerCoin.Coins += newAddCoins;
                        customerCoin.LastUpdateTime = DateTime.Now;
                    }
                    else
                    {
                        var cc = new CustomerCoin
                        {
                            CoinID = Guid.NewGuid(),
                            CreateTime = DateTime.Now,
                            Coins = newAddCoins,
                            CustomerID = model.CustomerOrders.First().CustomerID.Value,
                            LastUpdateTime = DateTime.Now
                        };
                        db.CustomerCoins.AddObject(cc);
                    }
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    Log.Error("ICustomerOrder.CloseOrder", ex);
                }
            }
        }
    }
}
